package com.dingyang.minio;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class MinIoService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinIOProperties properties;

    //获取文件后缀
    private String getSuffix(String fileName){
        return fileName.substring(fileName.lastIndexOf("."));
    }

    @SneakyThrows
    public String uploadFile(MultipartFile file){
        //文件的流对象
        InputStream inputStream = file.getInputStream();
        //上传的文件名
        String fileName = file.getOriginalFilename();
        //生成文件名
        String newName = UUID.randomUUID().toString();
        //后缀名计算
        String suffix = getSuffix(fileName);
        //文件文件名
        System.out.println("文件名："+fileName);
        fileName =newName+suffix;
        //文件文件名
        System.out.println("文件名："+fileName);
        //文件 进行上传
        PutObjectArgs poa = PutObjectArgs.builder()
                .stream(inputStream, file.getSize(), PutObjectArgs.MIN_MULTIPART_SIZE)
                .object(fileName)
                .contentType(file.getContentType())
                .bucket(properties.getBucket())
                .build();
        minioClient.putObject(poa);
        //返回文件名 ： 访问域名+桶+文件名S
        String url = properties.getUrl()+"/"+properties.getBucket()+"/"+fileName;
        return url;
    }


}
